class Vote < ActiveRecord::Base

  belongs_to :user
  belongs_to :feature_request

  validates_format_of :ip_address, :with => /^(\d{1,3}\.){3}\d{1,3}$/, :allow_blank => true
  validates_associated :user, :feature_request

  after_create :update_feature_request_rating

  def validate_on_create
    last_vote = Vote.find_last_by_user_id_and_feature_request_id(user_id, feature_request_id)
    if last_vote && last_vote.created_at.to_date.today?
      errors.add_to_base 'Votes are saved in a user-feature request daily basis!'
    end
  end

  private

  def update_feature_request_rating
    feature_request.increment!(:rating)
  end

end
